package cn.appliedata.base.zuul.filter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StringUtils;

//import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

//import cn.appliedata.common.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ErrorFilter extends ZuulFilter {
	private static final String ERROR_STATUS_CODE_KEY = "error.status_code";

    public static final String DEFAULT_ERR_MSG = "系统繁忙,请稍后再试";

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return false; //ctx.containsKey(ERROR_STATUS_CODE_KEY);
    }

    @Override
    public Object run() {       
        RequestContext ctx = RequestContext.getCurrentContext();

        try {
            HttpServletRequest request = ctx.getRequest();

            int statusCode = (Integer) ctx.get(ERROR_STATUS_CODE_KEY);
            String message = (String) ctx.get("error.message");
            if (ctx.containsKey("error.exception")) {
                Throwable e = (Exception) ctx.get("error.exception");
                Throwable re = getOriginException(e);
                if(re instanceof java.net.ConnectException){
                    message = "Real Service Connection refused";
                    log.warn("uri:{},error:{}" ,request.getRequestURI(),re.getMessage());
                }else if(re instanceof java.net.SocketTimeoutException){
                    message = "Real Service Timeout";
                    log.warn("uri:{},error:{}" ,request.getRequestURI(),re.getMessage());
                }else if(re instanceof com.netflix.client.ClientException){
                    message = re.getMessage();
                    log.warn("uri:{},error:{}" ,request.getRequestURI(),re.getMessage());
                }else{
                    log.warn("Error during filtering",e);
                }
            }

            if(StringUtils.isEmpty(message) || message.matches("\\s*"))message = DEFAULT_ERR_MSG;

            request.setAttribute("javax.servlet.error.status_code", statusCode);
            request.setAttribute("javax.servlet.error.message", message);

            ctx.setResponseStatusCode(500);
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            //ctx.setResponseBody(JSONObjecxt.toJSONString(new ResponseWrapper<>().setSuccess(false).setMsg(message)));
        } catch (Exception e) {
            String error = "Error during filtering[ErrorFilter]";
            log.error(error,e);
            ctx.setResponseStatusCode(500);
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            //ctx.setResponseBody(/*JSONObject.toJSONString(new ResponseWrapper<>().setSuccess(false).setMsg(error))*/);
        }
        return null;

    }

    private Throwable getOriginException(Throwable e){
        e = e.getCause();
        while(e.getCause() != null){
            e = e.getCause();
        }
        return e;
    }

}
